﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");

            ConfigurationBuilder configBuilder = new ConfigurationBuilder();
            configBuilder.AddJsonFile("config.json",
                optional: false /* 是否可选，设为false，文件必须存在 */,
                reloadOnChange: false /* 文件内容变更，重新加载 */);
            // 项目->属性->调试->命令行参数
            configBuilder.AddCommandLine(args);
            // 环境变量

            // 自定义
            configBuilder.Add(new FxConfigurationSource() { Path = "web.config" });

            IConfigurationRoot config = configBuilder.Build();

            string name = config["name"];
            string proxyAddress = config.GetSection("proxy:address").Value;
            Console.WriteLine($"name={name}, addr={proxyAddress}");

            string description = config["Description"];
            Console.WriteLine($"Description={description} from command line");

            string connstr1ConnectionString = config["connstr1:connectionString"];
            string connstr1ProviderName = config["connstr1:providerName"];
            Console.WriteLine($"connstr1, connectionString={connstr1ConnectionString}, providerName={connstr1ProviderName}, from web config");

            Proxy proxy = config.GetSection("proxy").Get<Proxy>();
            Console.WriteLine(proxy);
            Config cfg = config.Get<Config>();
            Console.WriteLine(cfg);

            ServiceCollection services = new ServiceCollection();
            services.AddOptions()
                .Configure<Config>(config)
                .Configure<Proxy>(o => config.GetSection("proxy").Bind(o));
            services.AddScoped<TestController>();
            services.AddScoped<TestController1>();

            using (var sp = services.BuildServiceProvider())
            {
                var ctrl = sp.GetRequiredService<TestController>();
                ctrl.Test();

                var ctrl1 = sp.GetRequiredService<TestController1>();
                ctrl1.Test();
            }
        }
    }
}
